<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <label for="">省</label>
    <select name="" id="sheng"></select>
    <label for="">市</label>
    <select name="" id="shi"></select>
    <label for="">区</label>
    <select name="" id="qu"></select>
    <script src="./cities.js"></script>
    <script>
      window.onload = function () {
        var sheng = document.getElementById("sheng");
        var a = '<option value="">请选择</option>';
        for (var i = 0; i < data.length; i++) {
          var item = data[i];
          a += `<option value="${item.code}">${item.name}</option>`;
        }
        sheng.innerHTML = a;
        /*-------------------------------------------------------------------*/
        var shi = document.getElementById("shi");
        sheng.addEventListener("change", function (e) {
          for (var i = 0; i < data.length; i++) {
            var item = data[i];
            if (item.code === e.target.value) {
              //找到数据了
              // 把该省下的城市全部渲染出来
              var cit = item.children;
              var b = '<option value="">请选择</option>';
              for (var i = 0; i < cit.length; i++) {
                var item = cit[i];
                b += `<option value="${item.code}">${item.name}</option>`;
              }
              shi.innerHTML = b;
            }
            // 边界处理，省份选择请选择时，清空市和区的下拉框
            if (e.target.value === "") {
              shi.innerHTML = `<option value="">请选择</option>`;
              qu.innerHTML = `<option value="">请选择</option>`;
            }
          }
        });
        /*--------------------------------------------------------------------------*/
        var qu = document.getElementById("qu");
        shi.addEventListener("change", function (e) {
          for (var i = 0; i < data.length; i++) {
            var item = data[i];
            var cit = item.children;
            for (var j = 0; j < cit?.length; j++) {
              var item1 = cit[j];
              if (item1.code === e.target.value) {
                var q = item1.children;
                var c = '<option value="">请选择</option>';
                for (var k = 0; k < q.length; k++) {
                  var item2 = q[k];
                  c += `<option value="${item2.code}">${item2.name}</option>`;
                }
                qu.innerHTML = c;
              }
              // 边界处理，市选择请选择时，清空区的下拉框
              if (e.target.value === "") {
                qu.innerHTML = `<option value="">请选择</option>`;
              }
            }
          }
        });
      };
    </script>
  </body>
</html>
